import React from "react";
import { Checkbox } from "antd";
import { flow } from "share/common";
import { DragSource, DropTarget } from "react-dnd";

class FieldItem extends React.Component {
  constructor(props) {
    super(props);
  }

  onFieldClick = (field) => {
    field.hide = !field.hide;
    this.setState({});
  };

  render() {
    const {
      connectDragSource,
      connectDropTarget,
      field,
      handleFieldVisibleChange,
      codeVisible,
      renderLanguage,
    } = this.props;
    return connectDragSource(connectDropTarget(
      <div className="report-field-wrapper">
        <Checkbox
          checked={!field.hide}
          className="report-field-checkbox"
          onChange={($e) => handleFieldVisibleChange($e, field)}/>
        <span className="field-content" onClick={() => this.onFieldClick(field)}>
          {field.columnDisplayName}
          {codeVisible && <span className="field-code-wrapper">({field.columnPropName})</span>}
          {renderLanguage(field)}
        </span>
      </div>))
  }
}

FieldItem.propTypes = {
  field: React.PropTypes.object.isRequired,  //对话框是否可见
  codeVisible: React.PropTypes.bool,  // 唯一编码是否可见
  handleFieldVisibleChange: React.PropTypes.func, // 字段隐藏切换处理方法
  renderLanguage: React.PropTypes.func, // 多语言组件渲染方法
  handleDND: React.PropTypes.func,  // 拖拽交换方法
  draggable: React.PropTypes.bool,  // 是否可拖拽
  index: React.PropTypes.number,
};

const DropTargetSpec = {
  drop(props, monitor, component) {
  },
  hover(props, monitor, component) {
    if (!component) return null;
    const dragNode = monitor.getItem();
    const dragIndex = dragNode.index; // 拖拽目标的Index
    const targetIndex = props.index; // 放置目标Index
    if (dragIndex === targetIndex) { // 如果拖拽目标和放置目标相同的话，停止执行
      return null;
    }
    // const hoverBoundingRect = (ReactDOM.findDOMNode(component)).getBoundingClientRect();//获取卡片的边框矩形
    // const {width, height, left, right, top, bottom} = hoverBoundingRect;
    props.handleDND(dragIndex, targetIndex); // 调用方法完成交换
    dragNode.index = targetIndex; // 重新赋值index，否则会出现无限交换情况
  },
};

const DropTargetCollect = (connect, monitor) => {
  return {
    connectDropTarget: connect.dropTarget(),
  }
};

const DragSourceSpec = {
  beginDrag(props, monitor, component) {
    return {
      index: props.index  // 用于hover时获取index
    }
  },
  canDrag(props) {
    return props.draggable
  }
};

const DragSourceCollect = (connect, monitor) => {
  return {
    connectDragSource: connect.dragSource(),
  }
};

const DragFieldItem = flow(
  DragSource("SORT_REPORT_FIELD", DragSourceSpec, DragSourceCollect),
  DropTarget("SORT_REPORT_FIELD", DropTargetSpec, DropTargetCollect)
)(FieldItem);

export default DragFieldItem
